<script setup lang="ts">
import { addCardAPI, getCardDetailAPI, updateCardAPI } from '@/apis/card';
import type { formCardData } from '@/types/card';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const formData = reactive<Partial<formCardData>>({
  personName: '',
  phoneNumber: "",
  carNumber: "",
  carBrand: ''
})
const formDataRules = reactive({
  personName: [
    {
      required: true,
      message: "请输入车主姓名",
      trigger: "blur",
    },
    { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, message: "请输入正确的姓名" }
  ],
  phoneNumber: [
    {
      required: true,
      message: "请输入联系方式",
      trigger: "blur",
    },
    { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: "请输入正确的联系方式" },


  ],
  carBrand: [
    {
      required: true,
      message: "请输入车辆品牌",
      trigger: "blur",
    },
    { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, message: "请输入正确的车辆品牌" }
  ],

  carNumber: [
    {
      required: true,
      message: "请输入车牌号码",
      trigger: "blur",
    },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/, message: "请输入正确的车牌号码" }
  ]

})
// 缴费信息表单
const feeForm = reactive({
  payTime: [], // 支付时间
  paymentAmount: '', // 支付金额
  paymentMethod: '', // 支付方式
});
// 缴费规则
const feeFormRules = ref({
  payTime: [
    {
      required: true,
      message: "请选择支付时间",
    },
  ],
  paymentAmount: [
    {
      required: true,
      message: "请输入支付金额",
      trigger: "blur",
    },
  ],
  paymentMethod: [
    {
      required: true,
      message: "请选择支付方式",
      trigger: "change",
    },
  ],
});
// 支付方式列表
const payMethodList = [
  {
    value: "Alipay",
    label: "支付宝",
  },
  {
    value: "WeChat",
    label: "微信",
  },
  {
    value: "Cash",
    label: "线下",
  },
];
const formDataRef = ref<FormInstance>()
const feeFormRef = ref<FormInstance>()
//路由器 -> 用于页面跳转
const router = useRouter();
// 路由 -> 获取页面路由参数
const route = useRoute();

const resetForm = async () => {

  try {
    await formDataRef.value?.validate()
    await feeFormRef.value?.validate()
    if (route.query.id) {
      await updateCardAPI({
        personName: formData.personName,
        carNumber: formData.carNumber,
        phoneNumber: formData.phoneNumber,
        carBrand: formData.carBrand,
        cardStartDate: feeForm.payTime[0],
        cardEndDate: feeForm.payTime[1],
        paymentMethod: feeForm.paymentMethod,
        paymentAmount: feeForm.paymentAmount,
        rechargeId: rechargeId.value,
        carInfoId: carInfoId.value
      } as formCardData)
      router.back();
      ElMessage({ message: "更新成功", type: "success" });
      return
    }
    await addCardAPI({
      personName: formData.personName,
      carNumber: formData.carNumber,
      phoneNumber: formData.phoneNumber,
      carBrand: formData.carBrand,
      cardStartDate: feeForm.payTime[0],
      cardEndDate: feeForm.payTime[1],
      paymentMethod: feeForm.paymentMethod,
      paymentAmount: feeForm.paymentAmount
    } as formCardData);
    // 成功轻提示
    ElMessage({ message: "校验成功", type: "success" });
    router.back();
  } catch (error) {
    console.log("错误信息", error);
    // 如果是请求错误，响应拦截器已处理，所以直接 return
    if ((error as any)?.response) return;
    // 否则是表单校验未通过，错误轻提示
    ElMessage({ message: "请按要求完成表单填写", type: "error" });
  }
}
// 重置表单
const onReset = async () => {
  // 弹窗确认
  await ElMessageBox.confirm("是否重置表单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  // 重置表单
  formDataRef.value?.resetFields();
  feeFormRef.value?.resetFields();
};
// 返回上一页
const goBack = async () => {
  // 弹窗确认
  await ElMessageBox.confirm("是否返回上一页，当前表单数据不做保留？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  // 返回上一页
  router.back();
};
onMounted(async () => {
  if (route.query.id) {
    await editorCard()
  }
})
const carInfoId = ref(0)
const rechargeId = ref(0)
const editorCard = async () => {
  const res = await getCardDetailAPI(route.query.id as string)
  formData.personName = res.data.personName,
    formData.phoneNumber = res.data.phoneNumber,
    formData.carBrand = res.data.carBrand,
    formData.carNumber = res.data.carNumber,
    feeForm.paymentAmount = String(res.data.paymentAmount),
    feeForm.paymentMethod = res.data.paymentMethod
  feeForm.payTime.unshift(res.data.cardStartDate as never)
  feeForm.payTime.push(res.data.cardEndDate as never)
  carInfoId.value = res.data.carInfoId
  rechargeId.value = res.data.rechargeId

}
</script>

<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="route.query.id ? '编辑月卡' : '增加月卡'" @back="goBack" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form label-width="100px" ref="formDataRef" :model="formData" :rules="formDataRules">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="formData.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input :maxlength="11" v-model="formData.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="formData.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="formData.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form label-width="100px" ref="feeFormRef" :model="feeForm" :rules="feeFormRules">
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker v-model="feeForm.payTime" value-format="YYYY-MM-DD" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option v-for="item in payMethodList" :key="item.label" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="resetForm">确定</el-button>
        {{ route.query.id }}---{{ carInfoId }}----{{ rechargeId }}
      </div>
    </footer>
  </div>
</template>

<script lang="ts" setup>
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }

    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>